#!/bin/bash
set -ex

readonly DOCKER_VER='20.10.8'

# 网易
readonly MIRROR='mirrors.163.com'
# 清华
# readonly MIRROR='mirrors.ustc.edu.cn'
# 阿里
# readonly MIRROR='mirrors.aliyun.com'

readonly UNNECESSARY_DIRS='
	/home /media/cdrom /media/floppy /media/usb /mnt /srv /usr/local/bin
	/usr/local/lib /usr/local/share
'

einfo() {
    printf '\n\033[1;31m> %s\033[0m\n' "$@" >&2  # bold red
}

upgrade(){
    einfo 'chroot: upgrade..'
    sed -i 's/archive.ubuntu.com/'$MIRROR'/g' /etc/apt/sources.list
    sed -i 's/security.ubuntu.com/'$MIRROR'/g' /etc/apt/sources.list
    # apt update
    # apt upgrade -y
}

# packages(){
#     einfo 'chroot: install packages..'
#     apt-get install $PACKAGES_NAMES
# }

timezone() {
    einfo 'chroot: install timezone..'
	local timezone="Asia/Shanghai"
	install -D /usr/share/zoneinfo/$timezone /etc/zoneinfo/$timezone
	ln -sf /etc/zoneinfo/$timezone /etc/localtime
}

passwd(){
    einfo 'chroot: install passwd..'
    sed -i '1d' /etc/passwd;sed -i '1i\root:x:0:0:root:/:/bin/bash' /etc/passwd
}

docker(){
    einfo 'chroot: install docker..'
    chmod 775 /usr/local/sbin/docker.sh
    chmod 775 /usr/local/sbin/generate-tls-key.sh
    mkdir -p /root
    mkdir -p /var/lib/wsl2-docker
    mkdir -p /usr/local/bin
    curl -fLo docker.tgz "$MIRROR/docker-ce/linux/static/stable/x86_64/docker-${DOCKER_VER}.tgz"
    tar xzf docker.tgz
    mv docker/* /usr/local/bin/
    rm -rf docker
    rm docker.tgz
    mkdir -p /etc/docker
    tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": [
"http://hub-mirror.c.163.com",
"https://docker.mirrors.ustc.edu.cn",
"https://registry.docker-cn.com"
]
}
EOF
}

clear(){
    einfo 'chroot: clear up..'
    apt-get autoclean
    apt-get clean
    apt-get autoremove
    rm -Rf /dev/*
    rm -Rf /tmp/*
    echo -e "# " -> /etc/resolv.conf
    for dir in $UNNECESSARY_DIRS; do
        rmdir -p "$dir" 2>/dev/null || true
    done
}

upgrade
timezone
passwd
docker
clear